using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
using System.Windows;
using System.Runtime.InteropServices;
using System.Collections.Generic;

namespace AttachChecker
{
	public partial class ThisApplication
    {
		[DllImport("user32")]
		public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        private void ThisApplication_ItemSend(object Item, ref bool Cancel)
        {
            Outlook.MailItem mail = (Outlook.MailItem)Item;

			string[] matches = new string[] { };

            if (IsMatch(mail, ref matches))
            {
                try
				{
					OutlookWindow win = new OutlookWindow(ActiveInspector());
					
					if (MessageBox.Show(win, "This mail contains the word '" + matches[0] + "', but there are no files attached. Would you like to send it anyway", "Attach Checker", MessageBoxButtons.YesNo) == DialogResult.No)
					{
						Cancel = true;
					}
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
				}
            }
        }

		private bool IsMatch(Outlook.MailItem mail, ref string[] matches)
		{
			string keyword = (string)Properties.Settings.Default["Keywords"];
			string divider = (string)Properties.Settings.Default["Divider"];

			Regex keywordRegex = new Regex(keyword);
			Regex dividerRegex = new Regex(divider);

			string body = mail.Body;

			if (dividerRegex.IsMatch(body))
			{
				// Strip out any text after the divider
				body = body.Substring(0, dividerRegex.Match(body).Index);
			}

			if ((mail.Attachments.Count == 0) && // There are no attachments
				(keywordRegex.IsMatch(mail.Subject) || // Keywords occur in the subject
				keywordRegex.IsMatch(body))) // Keywords occur in the body before the divider
			{
				MatchCollection matchCollection = keywordRegex.Matches(mail.Subject + body);

				List<string> matchList = new List<string>(matchCollection.Count);

				foreach (Match match in matchCollection)
				{
					matchList.Add(match.Value);
				}

				matches = matchList.ToArray();

				return true;
			}
			
			return false;
		}

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.ItemSend += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_ItemSendEventHandler(ThisApplication_ItemSend);
        }
        
        #endregion
    }
}
